<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 新米汇
 */
class XinmihuiController extends PayController{
    protected $config;
    protected $class;
	
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data=[];
        $data['version'] = '1.0';
        $data['customerid'] = $this->config['mch_id'];
        $data['sdorderno'] = $return['orderid'];
        $data['total_fee'] = number_format($return['amount'],2,'.','');
        switch($this->config['paytype']) {
            //微信
            case 1:
			case 2:
                $data['paytype'] = 'wechat';
                break;
            case 3:
            case 4:
                $data['paytype'] = 'alipay';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        //$data['bankcode'] = '';
        $data['notifyurl'] = $return['notifyurl'];
        $data['returnurl'] = $return['callbackurl'];
        $data['remark'] = 'zf';
        //$data['get_code'] = '';

        $str = "version={$data['version']}&customerid={$data['customerid']}&total_fee={$data['total_fee']}&sdorderno={$data['sdorderno']}&notifyurl={$data['notifyurl']}&returnurl={$data['returnurl']}&{$this->config['signkey']}";
        $data['sign'] = md5($str);

		$res = curl($this->config['gateway'], httpstr($data));
		
		$res = json_decode($res, true);
		if(!$res || empty($res)){
			$this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
		}
        
		$code = $res['h5_link'];
		if(!$code){
			if($res['msg']){
				$this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
			}
			
			$this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
		}
		
		$paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
				header("location:{$code}");exit;
                if(isMobile()){
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
       /*  file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        file_put_contents("a.txt",var_export($_GET,true."\r\n\r\n"), FILE_APPEND);
        file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", date('Y-m-d H:i:s',time())."\r\n\r\n", FILE_APPEND);

        $this->debug_callback(); */
		
		$p = I("post.");
		/* $p = array (
		  'customerid' => '11546',
		  'status' => '1',
		  'sdpayno' => 'ykalipay154746316656503',
		  'sdorderno' => '2019011418524523259',
		  'total_fee' => '10.00',
		  'paytype' => 'alipay',
		  'remark' => 'zf',
		  'sign' => 'ae5e6cc33a6fed5cb6979052ab937861',
		); */

        if(!$p || empty($p)){
            exit;
        }

        //获取订单信息
        $orderid = $p['sdorderno'];
        $find = $this->checkOrderNotify($orderid);

        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['sdpayno'])
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        if($p['respCode'] != 0){
            echo "pail_fail"; exit;
        }

        $sign = $p['sign'];
        unset($p['sign']);

        $str = "customerid={$p['customerid']}&status={$p['status']}&sdpayno={$p['sdpayno']}&sdorderno={$p['sdorderno']}&total_fee={$p['total_fee']}&paytype={$p['paytype']}&{$this->config['signkey']}";
		
        $sign2 = md5($str);
		
		//echo 'str: '.$str.'<br/>';
        //echo 'sign: '.$sign.'<br/>';
        //echo 'sign2:'.$sign2;exit;

        if($sign !== $sign2){
            exit("fail");
        }
		
		if($p['status'] !== '1'){
			echo 'pay fail'; exit;
		}

        $this->async($find['pay_orderid'], 'success');
    }

    public function callBackUrl(){

        echo '操作成功'; exit;
    }
}